﻿using System;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using YArchitech.Revit.RevitExtension;

namespace YArchitech.HVAC
{
	public class CalculateElevation
	{
		public CalculateElevation(double slope)
		{
			this.slope = slope;
		}

		public void MovePipe(UIDocument uiDoc)
		{
			try
			{
				Document document = uiDoc.Document;
				Reference reference = uiDoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new PipeSelectionFilter(), "选取一个管道");
				Element element = document.GetElement(reference);
				LocationCurve locationCurve = (element as Pipe).Location as LocationCurve;
				this.line = (locationCurve.Curve as Line);
				this.ptStart = this.line.GetEndPoint(0);
				this.ptEnd = this.line.GetEndPoint(1);
				double num = this.ptStart.DistanceTo(new XYZ(this.ptEnd.X, this.ptEnd.Y, this.ptStart.Z));
				XYZ xyz = uiDoc.Selection.PickPoint("请在管道上选择一点来确定坡度调整基点");
				if (!this.IsPointOnLine(xyz, this.ptStart, this.ptEnd, this.GetDiameter(element)))
				{
					TaskDialog.Show("盈建科提示", "选择的点不在管道上");
				}
				else
				{
					xyz = this.GetProject(xyz);
					double num2 = this.slope * num;
					double num3 = xyz.DistanceTo(this.ptStart) / this.ptStart.DistanceTo(this.ptEnd) * num2;
					double num4 = num2 - num3;
					XYZ endPoint = new XYZ(this.ptEnd.X, this.ptEnd.Y, xyz.Z + num4);
					Line curve = YJKLineEx.YJKGetBound(new XYZ(this.ptStart.X, this.ptStart.Y, xyz.Z - num3), endPoint);
					locationCurve.Curve = curve;
					ElementTransformUtils.MoveElement(document, element.Id, new XYZ(1E-05, 1E-05, 1E-05));
					ElementTransformUtils.MoveElement(document, element.Id, -1.0 * new XYZ(1E-05, 1E-05, 1E-05));
				}
			}
			catch (Exception ex)
			{
				ex.ToString();
			}
		}

		private double GetDiameter(Element elem)
		{
			string text = (elem as Pipe).get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM).AsValueString();
			text = text.Substring(0, text.Length - 2);
			return double.Parse(text) / 304.8;
		}

		public bool IsPointOnLine(XYZ xyz, XYZ startPoint, XYZ endPoint, double diameter)
		{
			bool result = false;
			XYZ xyz2 = new XYZ(startPoint.X, startPoint.Y, xyz.Z);
			XYZ xyz3 = new XYZ(endPoint.X, endPoint.Y, xyz.Z);
			if (xyz.DistanceTo(xyz2) + xyz.DistanceTo(xyz3) - xyz2.DistanceTo(xyz3) < diameter / 2.0)
			{
				result = true;
			}
			return result;
		}

		public XYZ GetProject(XYZ point)
		{
			IntersectionResult intersectionResult = new IntersectionResult();
			intersectionResult = this.line.Project(point);
			XYZ result = null;
			if (intersectionResult != null)
			{
				result = intersectionResult.XYZPoint;
			}
			return result;
		}

		private double slope;

		private Line line;

		private XYZ ptStart;

		private XYZ ptEnd;
	}
}
